﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace orderCreater
{
    public partial class FrmWdhOrder : Form
    {
        public OrderCreaterModel OCM = new OrderCreaterModel(ConfigurationManager.AppSettings["ConnStr-wdh"]);
        public FrmWdhOrder()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            this.sr_bgw.WorkerSupportsCancellation = true;   
            this.sr_btn_stop.Enabled = false;
            this.sr_tb_goodIds.Text = ConfigurationManager.AppSettings["goodsIds-wdhOrder"];
        }
        
        private void sr_bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;
            this.sr_btn_start.Enabled = false;
            this.sr_btn_stop.Enabled = true;
            this.sr_tb_priceArea.Enabled = false;
            this.sr_tb_goodIds.Enabled = false;
            this.sr_dt_time.Enabled = false;
            this.tb_sr_payPrice.Enabled = false;
            this.sr_tb_logs.Text = "";

            decimal total = 0;
            int count = 0;
            int post_err_cnt = 0;
            StringBuilder _logs = new StringBuilder();

            do
            {
                if (worker.CancellationPending || total > decimal.Parse(this.sr_tb_priceArea.Text))
                {

                    e.Cancel = true;

                    break;
                }
                else
                {
                    ///获取新增用户
                    WDH_REGISTER new_user = cb_user.Checked ? OCM.WDHExistUser() : OCM.WDHNewUser();
                    if (new_user.status == 200)
                    {
                        ///获取收货地址
                        WDH_AddrNormal new_addr = OCM.WDHNormalAddr();
                        if (new_addr.status == 200 && new_addr.data.Count > 0)
                        {
                            WDH_Buyer buyer = OCM.WDYGetBuyer(new_user.data.member_id);
                            WDH_Goods goods = OCM.WDHRandGoodsByIds(this.sr_tb_goodIds.Text.ToString());
                            string orderCode = OCM.CreateOrderCode();
                            string orderTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            if (bd_cb.Checked)
                            {
                                orderTime = OCM.CreateOrderTime(this.sr_dt_time.Value.ToString("yyyy-MM-dd"));
                            }
                            string requestTime = OCM.CreateSendTime(orderTime);
                            string orderRemarks = OCM.getWDHOrderRemark();
                            string payTime = OCM.CreatePayTime(orderTime, tb_jiange.Text);
                            string sql_order;
                            if (OCM.IsPay() && !this.cb_sr_notPay.Checked)
                            {
                                sql_order = @"INSERT INTO `db_order` (`orderCode`, `memberId`, `shopId`, `accepterName`, `accepterMobile`,"
                                    + "`provinceId`, `provinceName`, `cityId`, `cityName`, `districtId`, `districtName`, "
                                    + "`address`, `payStatusId`, `deliveryStatusId`, `orderStatusId`, `payTypeId`, `payTime`, `expressTypeId`, `expressNumber`, `expressPrice`, "
                                    + "`totalPrice`, `orderRemarks`, `returnGoodsMarks`, `ref1score`, `ref2score`, `ref3score`, `isView`, `isBill`, `billTypeId`, `billTitle`, `deliverTime`, `isIntegral`, `userIntegral`, `activityName`, `confirmTime`,"
                                    + "`arrivedTime`, `addTime`, `isQiangDan`, `QiangDanShopName`, `qdfbTime`, `qdcgTime`,`type_status`) VALUES ('"
                                    + orderCode + "', " + new_user.data.member_id + ", 0, '" + new_addr.data[0].name + "', '" + new_addr.data[0].mobile + "',"
                                    + new_addr.data[0].province_id + ", NULL, " + new_addr.data[0].city_id + ", NULL, " + new_addr.data[0].area_id + ",NULL,"
                                    + "'" + new_addr.data[0].address + "', 2, 1, 2, 2, '" + payTime + "', NULL, NULL, 0.00, "
                                    + goods.goodsPrice + ", '" + orderRemarks + "', NULL, 0.00, 0.00, 0.00, 0, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, '"
                                    + requestTime + "', '" + orderTime + "', 0, NULL, NULL, NULL,2);SELECT LAST_INSERT_ID();";
                            }
                            else
                            {
                                sql_order = @"INSERT INTO `db_order` (`orderCode`, `memberId`, `shopId`, `accepterName`, `accepterMobile`,"
                                    + "`provinceId`, `provinceName`, `cityId`, `cityName`, `districtId`, `districtName`, "
                                    + "`address`, `payStatusId`, `deliveryStatusId`, `orderStatusId`, `payTypeId`, `payTime`, `expressTypeId`, `expressNumber`, `expressPrice`, "
                                    + "`totalPrice`, `orderRemarks`, `returnGoodsMarks`, `ref1score`, `ref2score`, `ref3score`, `isView`, `isBill`, `billTypeId`, `billTitle`, `deliverTime`, `isIntegral`, `userIntegral`, `activityName`, `confirmTime`,"
                                    + "`arrivedTime`, `addTime`, `isQiangDan`, `QiangDanShopName`, `qdfbTime`, `qdcgTime`,`type_status`) VALUES ('"
                                    + orderCode + "', " + new_user.data.member_id + ", 0, '" + new_addr.data[0].name + "', '" + new_addr.data[0].mobile + "',"
                                    + new_addr.data[0].province_id + ", NULL, " + new_addr.data[0].city_id + ", NULL, " + new_addr.data[0].area_id + ",NULL,'"
                                    + new_addr.data[0].address + "', 1, 1, 1, 0, NULL, NULL, NULL, 0.00, "
                                    + goods.goodsPrice + ", '" + orderRemarks + "', NULL, 0.00, 0.00, 0.00, 0, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, '"
                                    + requestTime + "', '" + orderTime + "', 0, NULL, NULL, NULL,2);SELECT LAST_INSERT_ID();";
                            }
                            string order_id = OCM.ExecuteMySql(sql_order);
                            if (order_id != "" && order_id != "-1")
                            {
                                if (this.sync_alipay_cb.Checked && OCM.IsPay() && !this.cb_sr_notPay.Checked)
                                {
                                    syncAlipay(orderCode, goods.goodsPrice, buyer.memberMobile, buyer.realName, payTime);
                                }

                                _logs.Insert(0, new_addr.data[0].name + " " + new_addr.data[0].mobile + " " + new_addr.data[0].province_id + " " + new_addr.data[0].city_id + " " + new_addr.data[0].area_id + " " + new_addr.data[0].address + "\r\n");
                                this.sr_tb_logs.Text = _logs.ToString();
                                string sql_order_common = "INSERT INTO `db_order_item` ( `orderItemCode`, `orderId`, `goodsId`, `goodsName`, `goodsPrice`, `goodsLogoUrl`, `goodsQuantity`, `promotionType`, `expressPrice`, `goodsStandard`) VALUES ( NULL, " 
                                    + order_id + ", " + goods.goodsId + ", '" + goods.goodsName + "', " + goods.goodsPrice + ", 'http://app.wodinghua.com" + goods.goodsLogo + "', 1, 0, 0.00, '" + goods.goodsSub + "');";
                                OCM.ExecuteNonSql(sql_order_common);
                                Post_Msg pms1 = OCM.WDHUpdateUserBuyCount(new_user.data.member_id);
                                Post_Msg pms2 = OCM.WDHUpdateAddressCount(new_addr.data[0].id);

                                string _s_time = this.sr_dt_time.Value.ToShortDateString();
                                string _e_time = this.sr_dt_time.Value.AddDays(1).ToShortDateString();
                                string _totalStr = OCM.ExecuteMySql("select sum(totalPrice) from db_order where addTime>'" + _s_time + "' and addTime<'" + _e_time + "';");
                                this.lb_sr_pay.Text = OCM.ExecuteMySql("select sum(totalPrice) from db_order where addTime>'" + _s_time + "' and addTime<'" + _e_time + "' and payStatusId=2;");

                                try
                                {
                                    total = decimal.Parse(_totalStr);
                                }
                                catch
                                {
                                    total = 0;  
                                }
                                decimal total_pay = 0;
                                try
                                {
                                    total_pay = decimal.Parse(this.lb_sr_pay.Text);
                                }
                                catch
                                {
                                    total_pay = 0;
                                }
                                count += 1;

                                _logs.Insert(0, "[" + DateTime.Now + "]成功录入一条订单信息。\r\n");

                                this.sr_lb_status.Text = "运行中……";

                                this.sr_tb_logs.Text = _logs.ToString();

                                this.sr_lb_count.Text = count.ToString();

                                this.sr_lb_totalPrice.Text = total.ToString();


                                if (total_pay > decimal.Parse(this.tb_sr_payPrice.Text))
                                {
                                    this.cb_sr_notPay.Checked = true;
                                }
                            }
                            if (bd_cb.Checked != true)
                            {
                                Random rd_sl = new Random();
                                int t_sl = rd_sl.Next(5 * 1000, Int32.Parse(this.tb_jiange.Text) * 1000);
                                System.Threading.Thread.Sleep(t_sl);
                            }
                        }
                        else
                        {
                            _logs.Insert(0, "[" + DateTime.Now + "]获取收货地址失败：" + new_addr.msg + "。\r\n");
                            this.sr_tb_logs.Text = _logs.ToString();
                            post_err_cnt++;
                            if (post_err_cnt > 10)
                            {
                                this.sr_lb_status.Text = "停止中……";
                                sr_bgw.CancelAsync();
                            }
                        }
                    }
                    else
                    {
                        _logs.Insert(0, "[" + DateTime.Now + "]获取下单人信息失败：" + new_user.msg + "。\r\n");
                        this.sr_tb_logs.Text = _logs.ToString();
                        post_err_cnt++;
                        if (post_err_cnt > 10)
                        {
                            this.sr_lb_status.Text = "停止中……";
                            sr_bgw.CancelAsync();
                        }
                    }
                }
            } while (!worker.CancellationPending);

            this.sr_lb_status.Text = "已停止！";

            this.sr_btn_start.Enabled = true;

            this.sr_btn_stop.Enabled = false;

            this.sr_tb_priceArea.Enabled = true;

            this.sr_tb_goodIds.Enabled = true;

            this.sr_dt_time.Enabled = true;

            this.tb_sr_payPrice.Enabled = true;
            
        }
        private void sr_bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                this.sr_lb_status.Text = "已停止！";
            }
        }

        private void sr_btn_start_Click(object sender, EventArgs e)
        {
            if (this.sr_tb_priceArea.Text.Length < 1) 
            {
                MessageBox.Show("请输入当日总金额。");
            }
            else if (this.tb_sr_payPrice.Text.Length < 1)
            {
                MessageBox.Show("请输入支付金额。");
            }
            else if (this.sr_tb_goodIds.Text.Length < 1)
            {
                MessageBox.Show("请输入产品ID。");
            }
            else 
            {
                this.sr_lb_status.Text = "系统初始化中……";

                this.sr_bgw.RunWorkerAsync();
            }
            
        }

        private void sr_btn_stop_Click(object sender, EventArgs e)
        {
            this.sr_lb_status.Text = "停止中……";

            sr_bgw.CancelAsync();
        }

        public static string syncAlipay(string _orderSn, string _orderPrice, string _account, string _fullName, string _tradeTime)
        {
            try
            {
                string url = "orderNo=" + _orderSn + "&";
                url = url + "tradeAmount=" + _orderPrice + "&";
                url = url + "otherAccountEmail=" + _account + "&";
                url = url + "otherAccountFullname=" + _fullName + "&";
                url = url + "sourceType=" + 2 + "&"; // 来源:1为531,2为我订花
                url = url + "tradeTime=" + _tradeTime;
                // string formUrl = "http://sync?.qqxhsd.com/api/trade/add";
                string formUrl = "https://alipay.22ca.com/index.php/Api/insertOrder3";
                string formData = url;                               //提交的参数

                //注意提交的编码 这边是需要改变的 这边默认的是Default：系统当前编码
                byte[] postData = Encoding.UTF8.GetBytes(formData);

                // 设置提交的相关参数 
                HttpWebRequest request = WebRequest.Create(formUrl) as HttpWebRequest;
                Encoding myEncoding = Encoding.UTF8;
                request.Method = "POST";
                request.KeepAlive = false;
                request.AllowAutoRedirect = true;
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                request.ContentLength = postData.Length;

                // 提交请求数据 
                System.IO.Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();

                HttpWebResponse response;
                Stream responseStream;
                StreamReader reader;
                string srcString;
                response = request.GetResponse() as HttpWebResponse;
                responseStream = response.GetResponseStream();
                reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
                srcString = reader.ReadToEnd();
                string result = srcString;   //返回值赋值
                reader.Close();
                return result;
            }
            catch
            {
                return "error";
            }
        }

        private void bd_cb_CheckedChanged(object sender, EventArgs e)
        {
            if (this.bd_cb.Checked == true)
            {
                this.sr_dt_time.Enabled = true;
            }
            else
            {
                this.sr_dt_time.Enabled = false;

            }
        }

        private void sr_tb_priceArea_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键  
            {
                if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字  
                {
                    e.Handled = true;
                }
            }
        }
    }
}
